const registry = require('regedit');
const path = require('path');
const remote = require('electron').remote
if (process.env.NODE_ENV === 'production') {
    console.log(path.join(path.dirname(remote.app.getPath('exe')), 'resources', 'vbs'));
    registry.setExternalVBSLocation(path.join(path.dirname(remote.app.getPath('exe')), 'resources', 'vbs'));
}
const { spawn } = require('child_process');
const { exec } = require('child_process');
const { shell } = require('electron')

/**
 * 打开或者关闭PPT，用于上下课
 */
export class ShowPpt {

    constructor(){
        this.pptExe = '';//ppt的执行程序
        this.prePids = [];//第一次查询的pids
        this.currentPid = [];//本次打开的ppt的pid
    }

    openPpt(pptPath){
        // 使用系统默认方式打开PPT
        // shell.openItem(pptPath);

        
        let _this = this;
        // 读取注册表，获取PPT的安装路径
        _this.readRegVaule('HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\powerpnt.exe', function (error, values) {
            if (error) {
                _this.fillTaskList("wps.exe");
                // exec(pptPath);
                shell.openItem(pptPath);
            }else {
                if (values) {
                    try {
                        let version = values.Path.value.match(/[0-9]+\\$/)[0]
                        // 低于office 2013
                        if(parseInt(version)<14){
                            // _this.fillTaskList("wps.exe");
                            shell.openItem(pptPath);
                            return
                        }
                        // 获取POWERPNT.exe的路径
                        let powerPntPath = values.Path.value + '\\POWERPNT.EXE';
                        let args = ['/s', pptPath];
                        _this.fillTaskList("POWERPNT.EXE");
                        spawn(powerPntPath, args, {detached: true })
                    } catch (error) {
                        // 打开失败，使用系统默认方式打开PPT
                        _this.fillTaskList("wps.exe");
                        // exec(pptPath);
                        shell.openItem(pptPath);
                    }
                } else {
                    // 打开失败，使用系统默认方式打开PPT
                    _this.fillTaskList("wps.exe");
                    // exec(pptPath);
                    shell.openItem(pptPath);
                }
            }
        })
    }

    shutDownPpt(){
        let _this = this;
        if(this.pptExe) {
            this.findTaskList(this.pptExe, 2).then(() => {
                setTimeout(function () {// 1s之后执行杀进程操作
                    for(let i = 0; i < _this.currentPid.length; i++){
                        exec("taskkill /pid " + _this.currentPid[i] + " -f");
                    }
                }, 1000);
            });
        }
    }

    readRegVaule(regPath, callback){
        let err = null;
        registry.list(regPath, (error, result) => {
            if (error) {
                // console.error("readRegVaule error", error);
                if (callback) {
                    err = error
                    callback(err)
                }
            }
            if (result) {
                let values = result[regPath].values;
                callback(err, values);
            }
        })
    }

    fillTaskList(exeName) {
        let _this = this;
        this.currentPid = [];
        this.prePids = [];
        this.pptExe = exeName;
        this.findTaskList(_this.pptExe, 1).then(() => {});
    }

    /**
     * 查找所有的任务集合
     * @param taskName
     * @param sortIndex 取值 1， 2   1：初始化prePids  2：初始化currentPid
     * @return {Promise<void>}
     */
    async findTaskList(taskName, sortIndex){
        let _this = this;
        const { stdout, stderr } = await exec("tasklist | findstr /i " + taskName);

        let promise = new Promise(resolve => {
            stdout.on("data", (chunk) => {
                let result = new Buffer(chunk).toString("utf8");
                result = result.split('\n');
                let pids = [];
                result.forEach(temp => {
                    let pid = [];
                    temp = temp.replace(/\s*/g,"");
                    if(taskName === "wps.exe"){
                        pid = temp.match(/wps.exe(\S*)Console/);
                    }else if(taskName === "POWERPNT.EXE"){
                        pid = temp.match(/POWERPNT.EXE(\S*)Console/);
                    }
                    if(pid instanceof Array && pid.length === 2){
                        pid = pid[1];
                        pids.push(pid);
                    }
                });
                if(sortIndex === 1){
                    _this.prePids = pids;
                    console.log("prePids", _this.prePids)
                }else if(sortIndex === 2){//PPT进程全部杀掉
                    _this.currentPid = pids;
                    console.log("currentPid", _this.currentPid)
                }
                resolve("");
            })
        });
        let result = await promise.then(() => {});
        return result;
    }
}
